package com.lm.scau.framedemos.Utils;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;
import java.util.regex.Pattern;

/**
 * 提供一些常用字符串处理方法
 *
 * @author JoyCode workshop
 * @update Bloom
 */
public class StringUtil {
	public static final String UP_ARROW = "↑";
	public static final String LEFT_ARROW = "↑";

	/**
	 * 判断当前字符串是否为null|""
	 *
	 * @param str 目标string
	 * @return
	 */
	public static boolean isBlank(String str) {
		return (str == null) || str.equals("");
	}

	/**
	 * 判断当前字符串是否不为null
	 *
	 * @param serviceUrl 目标string
	 * @return
	 */
	public static boolean isNotBlank(String serviceUrl) {
		return !isBlank(serviceUrl);
	}

	public static boolean isEquals(String one, String another) {
		if (isNotBlank(one) && isNotBlank(another) && one.equals(another)) {
			return true;
		} else if (one == null && another == null) {
			return true;
		} else if (one != null && another != null && one.equals(another)) {//a、b为空串
			return true;
		}
		return false;
	}
	// private static int addLine(java.util.Vector v, StringBuffer sb) {
	// v.addElement(sb.toString());
	// sb.delete(0, sb.length());
	// return 0;
	// }

	/**
	 * 根据屏幕宽度，将字符串转换为以行为单位的字符行vector
	 *
	 * @param displayText
	 * @return
	 */
	/*
     * public static Vector separateString(String displayText) { java.util.Vector v = new
     * java.util.Vector(); int wd = 0; char word; StringBuffer sb = new StringBuffer(); int length =
     * displayText.length(); int lines = 0; int width = Platform.WIDTH - 10; Font font =
     * Font.getDefaultFont(); for (int i = 0; i < length; i++) { word = displayText.charAt(i);
     * sb.append(word); wd += font.charWidth(word); if (wd > width || word == '\n') { lines++; wd =
     * 0; } if (i == length - 1 || lines > 15) { sb.append("\n" + createSpaceLine(font, width));
     * lines = addLine(v, sb); wd = 0; } } return v; }
     */

	/**
	 * 创建一个指定宽度的分割行
	 *
	 * @return
	 */
    /*
     * public static String createSeparatorLine() { Font font = Font.getDefaultFont(); int width =
     * Platform.WIDTH - font.charWidth('-') * 2; return createSpaceLine(font, width, '-'); }
     */

	/**
	 * 对字符串信息进行调整，去除；，用\n代替
	 *
	 * @param content
	 * @return
	 */
	public static String getAdjustDisplayContent(String content) {
		if (!StringUtil.isBlank(content)) {
			content = content.replace(';', '\n');
		}
		return content;
	}

	/**
	 * 对字符串用指定符合进行拆分,如果为空则插入下一个字符串
	 *
	 * @param str
	 * @param ch
	 * @return
	 */
	public static String[] split(String str, char ch) {
		Vector v = new Vector();
		int start = 0;
		int pos = 0;
		if (str == null)
			return null;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ch) {
				String xx = str.substring(start, i);
				if (isNotBlank(xx)) {
					v.addElement(xx);
				}
				start = i + 1;
				pos = i;
			}
		}
		if (pos < str.length()) {
			pos = pos > 0 ? pos + 1 : pos;
			String xx = str.substring(pos);
			if (isNotBlank(xx)) {
				v.addElement(xx);
			}
		}
		String results[] = convertVector2String(v);

		return results;
	}

	/**
	 * 对字符串用指定符合进行拆分,如果为空则插入一个空格
	 *
	 * @param str
	 * @param ch
	 * @return
	 */
	public static String[] splitInsertSpaceDefault(String str, char ch) {
		Vector v = new Vector();
		int start = 0;
		int pos = 0;
		if (str == null)
			return null;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == ch) {
				String xx = str.substring(start, i);
				if (isNotBlank(xx)) {
					v.addElement(xx);
				} else {
					v.addElement(" ");
				}
				start = i + 1;
				pos = i;
			}
		}
		if (pos < str.length()) {
			pos = pos > 0 ? pos + 1 : pos;
			String xx = str.substring(pos);
			if (isNotBlank(xx)) {
				v.addElement(xx);
			} else {
				v.addElement(" ");
			}
		}
		String results[] = convertVector2String(v);

		return results;
	}

	/**
	 * 将vecotor转换为数组对象
	 * <p/>
	 * 此方法完全多余
	 *
	 * @param temp
	 * @return
	 */
	public static String[] convertVector2String(Vector temp) {

		String[] result = null;
		int tsize = temp.size();
		if (tsize > 0) {
			result = new String[tsize];
			temp.copyInto(result);
		}
		return result;
	}

	/**
	 * 将字符数组中的内容用；连接起来
	 *
	 * @param receiverlist
	 * @return
	 */
	public static String concate(String[] receiverlist) {
		StringBuffer sb = new StringBuffer();
		if (receiverlist.length == 1) {
			return receiverlist[0];
		}
		for (int i = 0; i < receiverlist.length; i++) {
			sb.append(receiverlist[i] + ";");
		}
		return sb.toString();
	}

	/**
	 * 截取指定长度的字符串
	 *
	 * @param value
	 * @param maxSize
	 * @return
	 */
    /*
     * public static String truncateStr(String value, int maxSize) { String temp =
     * KUtil.convert(value); if (temp.length() > maxSize) { temp = temp.substring(0, maxSize); }
     * return temp; }
     */

	/**
	 * 移除当前字符数组的null 值
	 *
	 * @param fixedUserList
	 * @return
	 */
	public static String[] removeNullValue(String[] fixedUserList) {
		int size = fixedUserList.length;
		Vector v = new Vector();
		for (int i = 0; i < size; i++) {
			if (fixedUserList[i] != null) {
				v.addElement(fixedUserList[i]);
			}
		}
		String temp[] = new String[v.size()];
		v.copyInto(temp);
		v = null;
		return temp;
	}

	/**
	 * 将字符串按换行符
	 *
	 * @param value
	 * @return
	 */
	public static String[] getLines(String value) {
		if (isBlank(value)) {
			return null;
		}
		int count = 1;
		Vector v = new Vector();
		StringBuffer line = new StringBuffer();
		v.addElement(line);
		for (int i = 0; i < value.length(); i++) {
			if ((value.charAt(i) == '\n') && (i != value.length() - 1)) {
				count++;
				line = null;
				line = new StringBuffer();
				v.addElement(line);
			}
			line.append(value.charAt(i));
		}
		String[] lines = new String[v.size()];
		for (int i = 0; i < lines.length; i++) {
			lines[i] = ((StringBuffer) v.elementAt(i)).toString();
		}
		return lines;
	}

	/**
	 * 返回指定数组中长度最大的一个
	 *
	 * @param values
	 * @return
	 */
	public static int getMaxLineLength(String[] values) {
		int max = 0;
		for (int i = 0; i < values.length; i++) {
			if ((values[i] != null) && (values[i].length() > max)) {
				max = values[i].length();
			}
		}
		return max;
	}

	/**
	 * 返回不带报名的实际类名
	 *
	 * @param obj
	 * @return
	 */
	public static String getSimpleClassName(Object obj) {
		String className = obj.getClass().getName();
		int pos = className.lastIndexOf('.');
		if (pos > 0) {
			className = className.substring(pos + 1);
		}
		return className;
	}

	/**
	 * 对一个数组进行排序，使用普通的冒泡法
	 *
	 * @param target
	 * @return
	 */
	public static String[] sort(String[] target) {
		for (int i = 0; i < target.length; i++) {
			for (int j = 1; j < target.length - i; j++) {
				if (target[j].compareTo(target[j - 1]) < 0) {
					String temp = target[j];
					target[j] = target[j - 1];
					target[j - 1] = temp;
				}
			}
		}

		return target;
	}

	/**
	 * 过滤值，返回true大于6位的数字，false非大于6位的数字
	 *
	 * @param obj
	 * @return
	 */
	public static boolean filterNumber(Object obj) {
		try {
			long number = Long.parseLong((String) obj);
			if (number >= 100000) {
				return true;
			}

		} catch (Exception e) {
			return false;
		}
		return false;
	}

	/***
	 * 过滤空字符串
	 *
	 * @param str
	 * @return
	 */
	public static String filterULLString(String str) {
		if (str != null)
			return str;
		return "";
	}

	/**
	 * 高亮度显示字符串中的部分字符
	 *
	 * @param destStr 原字符串
	 * @param subStr  高亮显示的部分
	 * @param color   [0] 高亮显示部分的颜色
	 */
	public static SpannableStringBuilder hightLinghtString(String destStr, String subStr, int color) {
		SpannableStringBuilder style = new SpannableStringBuilder(null == destStr ? "" : destStr);

		if (null == destStr || "".equals(destStr) || "".equals(subStr)) {
			return style;
		}
		int start = destStr.lastIndexOf(subStr);
		if (start != -1) {
			style.setSpan(new ForegroundColorSpan(color), start, start + subStr.length(),
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
		}
		return style;
	}

	public static CharSequence getStringFromInputStream(InputStream in) {
		InputStreamReader inputStreamReader = null;
		try {
			inputStreamReader = new InputStreamReader(in, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		BufferedReader reader = new BufferedReader(inputStreamReader);
		StringBuffer sb = new StringBuffer("");
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	// 设置TextFild标题的长度
	public static String getTextFildTitle(String strName) {
		int strLength = 0;
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isGB2312(c)) {
				strLength += 2;
			} else {
				strLength += 1;
			}
			if (strLength >= 16) {
				return strName.substring(0, i);
			}
		}

		return strName;
	}

	// get the String length
	public static int getStringLength(String strName) {
		int strLength = 0;
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isGB2312(c)) {
				strLength += 2;
			} else {
				strLength += 1;
			}
		}
		return strLength;
	}

	public static boolean isGB2312(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * getAlpha: 获取拼音的首个字母 <通讯录模块字母排序使用。>
	 */
	public static String getAlpha(String str) {
		if (str == null) {
			return "#";
		}
		if (str.trim().length() == 0) {
			return "#";
		}
		char c = str.trim().substring(0, 1).charAt(0);
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase();
		} else {
			return "#";
		}
	}


	/**
	 * getCommonSubstring: 最长公有子序列
	 *
	 * @param str1 字符串一
	 * @param str2 字符串二
	 * @return 返回两个字符串比较的连续相同字符的个数
	 */
	public static int getCommonSubstring(String str1, String str2) {

		if (str1 == null || str2 == null) {
			return 0;
		}
		int len1, len2, len, s1_start, s2_start, curmax, max;


		len1 = str1.length();
		len2 = str2.length();
		len = len1 + len2;
		max = 0;
		for (int i = 0; i < len; i++) {

			s1_start = s2_start = 0;

			if (i < len1) {
				s1_start = len1 - i;// 每次开始匹配的起始位置
			} else {
				s2_start = i - len1;
			}

			curmax = 0;
			for (int idx = 0; (s1_start + idx < len1) && (s2_start + idx < len2); idx++) {

				if (str1.charAt(s1_start + idx) == str2.charAt(s2_start + idx)) {

					curmax++;

				} else {// 只要有一个不相等，就说明相等的公共字符断了，不连续了，要保存curmax与max中的最大值，并将curmax重置为0

					max = curmax > max ? curmax : max;
					curmax = 0;
				}
			}
			max = curmax > max ? curmax : max;
		}
		return max;
	}


	/**
	 * 从string[] 转到string
	 *
	 * @param sttArr
	 * @return
	 */
	public static String getArrayString(String[] sttArr) {
		StringBuffer attStr = new StringBuffer();
		for (String str : sttArr) {
			attStr.append(str + ",");
		}
		if (attStr.length() > 0) {
			return attStr.substring(0, attStr.length() - 1);
		}
		return null;
	}

	/**
	 * 替换字符串指定位置的值
	 * @param index 替换字符串的下标
	 * @param res 字符串
	 * @param str 替换值
	 * @return 新的字符串
	 */
	public static String replaceIndex(int index, String res, String str){
		return res.substring(0, index)+str+res.substring(index+1);
	}

	/**
	 *
	 * @param rawFormat
	 * @return
     */
	public static Integer getIntegerPartCount(String rawFormat) {
		String intPartString = rawFormat.substring(0, rawFormat.indexOf(".")); //记录整数部分
		if(!StringUtil.isBlank(intPartString)) {
			return Integer.parseInt(intPartString);
		} else {
			return 0;
		}
	}

	/**
	 *
	 * @param rawFormat
	 * @return
     */
	public static Integer getDecimalPartCount(String rawFormat) {
		String decPsrtString = rawFormat.substring(rawFormat.indexOf(".") + 1, rawFormat.indexOf("n")); //记录小数部分
		if (!StringUtil.isBlank(decPsrtString)) {
			return Integer.parseInt(decPsrtString);
		} else {
			return 0;
		}
	}
}
